package main

import (
	"fmt"
	"os"
	"bufio"
)

type intG func() int

func fibonacci() intG{
	a, b := 0, 1
	return func() int {
		a, b = b, a+b
		return a
	}
}


func tryDefer() {
	defer fmt.Println(1)
	defer fmt.Println(2)
	fmt.Println(3)
}

func tryDefer1() {  //参数在defer语句是计算
	for i := 0; i < 100; i++ {
		defer fmt.Println(i)
		if i==30 {
			panic("printed too many")
		}
	}
}

func writeFile(filename string)  {
	file, err := os.Create(filename)  //创建文件就需要defer file.close
	if err != nil{
		panic(err)
	}

	defer file.Close()
	wirter := bufio.NewWriter(file)  //bufio  这个接口函数是先将内容存在内存里，等内存达到一定值，然后再写到磁盘,就是先缓冲的意思吧
	defer wirter.Flush()

	f := fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(wirter, f())
	}



}

func main() {
	tryDefer()

	tryDefer1()
	writeFile("fib.txt")
}
